message("---------------- LibDemo ---------------------")

#message("PROJECT_BINARY_DIR = ${PROJECT_BINARY_DIR}")

add_library(libDemo "libDemo.cpp") # 如果库是单头文件库，可以加上INTERFACE限定符，指明它不生成任何二进制文件

# 可以把add_xxx(n) 的n看成是一个目标，每个目标都有各自的属性
# PRIVATE INTERFACE PUBLIC是用来控制这些属性是否能被依赖于本目标的其它目标所访问 (例如通过 add_subdirectory)

# 公有包含，把搜索目录添加到INTERFACE_INCLUDE_DIRECTORIES 和 INCLUDE_DIRECTORIES
#target_include_directories(libDemo PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

# 接口包含，仅把搜索目录添加到INTERFACE_INCLUDE_DIRECTORIES，
# INTERFACE_INCLUDE_DIRECTORIES 仅在依赖本target的其它target构建时会可被访问 (本target不能访问)
target_include_directories(libDemo INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})

# 私有包含，仅把搜索目录添加到INCLUDE_DIRECTORIES，
# INCLUDE_DIRECTORIES只有在本target才能访问(从中获取路径搜索头文件)
target_include_directories(libDemo PRIVATE "private")

message("CMAKE_CURRENT_SOURCE_DIR = ${CMAKE_CURRENT_SOURCE_DIR}")

set(LibDemoInstallDir "${PROJECT_BINARY_DIR}/Install") # 设定临时变量

# 指定目标的安装路径, 如果使用相对路径，它会以CMAKE_INSTALL_PREFIX作为前缀
install(TARGETS libDemo DESTINATION lib)
install(FILES libDemo.h DESTINATION include)
message("CMAKE_INSTALL_PREFIX = ${CMAKE_INSTALL_PREFIX}")
message("Install libDemo to ${LibDemoInstallDir}/lib")

# 用户自定义命令示例
# OUTPUT模式的自义命令只有它的输出文件被其它target依赖时才会被执行
add_custom_command(
  OUTPUT ${PROJECT_BINARY_DIR}/custom_cmd.txt
#  COMMAND echo 123 > ${PROJECT_BINARY_DIR}/custom_cmd.txt

# cmake平台无关命令使用方法， 平台无关命令可以 cmake.exe -E help进行查看
  COMMAND ${CMAKE_COMMAND} -E echo 234 > ${PROJECT_BINARY_DIR}/custom_cmd.txt
#  DEPENDS libDemo # 依赖
  )

file(TO_NATIVE_PATH ${PROJECT_BINARY_DIR}/custom_cmd.txt PPATH) # 将路径分隔符转换为平台特定的
if(CMAKE_SYSTEM_NAME MATCHES "Windows")  # 判断平台
    SET(CMD_CAT "type")
elseif(CMAKE_SYSTEM_NAME MATCHES "Linux")
    SET(CMD_CAT "cat")
endif()

add_custom_target(
    print-custom-txt ALL
    COMMAND ${CMD_CAT} ${PPATH}
    DEPENDS ${PROJECT_BINARY_DIR}/custom_cmd.txt
)

# 根据BUILD_SHARED_LIBS判断是否导出接口到共享库
if(BUILD_SHARED_LIBS)
    # 添加编译时的宏定义 EXPORT_LIBDEMO
    target_compile_definitions(libDemo PRIVATE "EXPORT_LIBDEMO")
endif()

# 指定生成代码位置无关库的方法
# 一般用于解决代码位置无关的库无法连接到代码位置相关的库问题，
# 强制把代码位置相关的库指定成代码位置无关可解决问题
# 共享库默认是代码位置无关的，这里只是设定示例
set_target_properties(libDemo PROPERTIES
    POSITION_INDEPENDENT_CODE ${BUILD_SHARED_LIBS}
    )


message("---------------- LibDemo ---------------------")


